import { useMemo } from 'react'
import { IProductInfoResponse } from '../inteface/product-info'
import { QuotationCategory } from '../constants'

interface CustomizedMaterial {
  categoryName: string
  subCategories: {
    id: number
    title: string
    material: {
      id: number
      name: string
      price: number
    }
  }[]
}

interface CustomizedMaterials {
  [categoryId: string]: CustomizedMaterial
}

interface UsePackageQuotationParams {
  productInfoData: IProductInfoResponse | undefined
  customizedMaterials: CustomizedMaterials
  showCategoryCustomizeButtons: boolean
}

interface PackageQuotation {
  categories: QuotationCategory[]
  total: number
}

/**
 * 构建类别的费用明细
 */
const buildCategoryQuotation = (
  categoryId: number | string,
  categoryName: string,
  customized: CustomizedMaterial | undefined,
  defaultSubCategories?: any[],
  defaultTotal?: number | string,
) => {
  if (customized) {
    // 使用定制材料的价格
    const items = customized.subCategories.map((subCat) => ({
      name: subCat.title,
      key: subCat.id,
      price: subCat.material.price + '',
    }))
    const total = customized.subCategories.reduce((sum, subCat) => sum + subCat.material.price, 0)

    return {
      category: categoryName,
      key: categoryId,
      items,
      total,
    }
  } else if (defaultSubCategories) {
    // 使用默认套餐价格
    return {
      category: categoryName,
      key: categoryId,
      items: defaultSubCategories.map((subCategory) => ({
        name: subCategory.title,
        key: subCategory.id,
        price: subCategory.totalPrice + '',
      })),
      total: defaultTotal || 0,
    }
  } else {
    // 空白待定制项
    return {
      category: categoryName,
      key: categoryId,
      items: [],
      total: 0,
    }
  }
}

/**
 * 计算总价
 */
const calculateTotalPrice = (categories: QuotationCategory[]): number => {
  return categories.reduce((sum, category) => {
    return sum + (typeof category.total === 'number' ? category.total : parseFloat(category.total as string) || 0)
  }, 0)
}

/**
 * usePackageQuotation Hook
 *
 * 计算套餐费用明细，包括：
 * 1. 默认套餐价格
 * 2. 用户定制后的价格
 * 3. 新增定制类别的价格
 *
 * @param productInfoData - 产品信息
 * @param customizedMaterials - 用户定制的材料
 * @param showCategoryCustomizeButtons - 是否显示类别定制按钮
 * @returns 费用明细和总价
 */
export const usePackageQuotation = ({
  productInfoData,
  customizedMaterials,
  showCategoryCustomizeButtons,
}: UsePackageQuotationParams): PackageQuotation => {
  return useMemo(() => {
    const packageMaterials = productInfoData?.product.packageMaterials

    // 构建基础类别数据（来自默认套餐）
    const baseCategories: QuotationCategory[] =
      packageMaterials?.categories?.map((category) => {
        const customized = customizedMaterials[category.id]
        return buildCategoryQuotation(
          category.id,
          category.categoryName,
          customized,
          category.subCategories,
          category.totalPrice,
        )
      }) || []

    // 添加新定制的类别（不在默认套餐中的）
    if (showCategoryCustomizeButtons && productInfoData?.product.availableMaterials) {
      const existingCategoryIds = new Set(baseCategories.map((c) => c.key))

      productInfoData.product.availableMaterials.forEach((availableMaterial) => {
        // 如果该类别已经在基础类别中，跳过
        if (existingCategoryIds.has(availableMaterial.id)) {
          return
        }

        const customized = customizedMaterials[availableMaterial.id]
        const newCategory = buildCategoryQuotation(
          availableMaterial.id,
          availableMaterial.categoryName,
          customized,
        )

        baseCategories.push(newCategory)
      })
    }

    // 计算总价
    const totalPrice = calculateTotalPrice(baseCategories)

    return {
      categories: baseCategories,
      total: totalPrice,
    }
  }, [productInfoData, customizedMaterials, showCategoryCustomizeButtons])
}

